package cn.edu.tjut.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.edu.tjut.bean.AdminBean;
import cn.edu.tjut.bean.StudentBean;
import cn.edu.tjut.bean.TeacherBean;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class UserLoginInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 在prehandle方法中，使用返回值进行拦截处理： 返回false -- 进行拦截； 返回true --
		// 放行，进入后续的拦截器或controller
		// 对于登录请求的url连接进行识别，并允许其通过拦截器
		// 注意：这里由于是使用url进行识别，所以在编程中需要将登陆的请求url名和
		// 和非登录的请求url名进行人为区别

		if (request.getRequestURI().contains("/logined")) {
			// 检测出登陆请求，进行放行
			return true;
		}
		AdminBean adminB = (AdminBean) request.getSession().getAttribute("userA");
		StudentBean stuB = (StudentBean) request.getSession().getAttribute("userS");
		TeacherBean teaB = (TeacherBean) request.getSession().getAttribute("userT");
		if ((adminB != null && adminB.getAdminAccont() != null && !adminB.getAdminAccont().equals(""))
				|| (stuB != null && stuB.getStuId() != null && !stuB.getStuId().equals(""))
				|| (teaB != null && teaB.getTeaId() != null && !teaB.getTeaId().equals(""))) {
			// 用户信息验证成功
			// 放行
			return true;
		} else {
			// 用户验证失败，进行拦截
			// 跳转回登录页面
			// 重定向
			response.sendRedirect("WEB-INF/views/index.jsp");
			return false;
		}
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

}
